package com.gome.axwl.aoc.web.controller.settleMananger;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.anxl.sso.client.api.Account;
import com.anxl.sso.client.api.AccountInfo;
import com.anxl.sso.client.api.Token;
import com.anxl.sso.client.support.AnxlSsoSupport;
import com.gome.axwl.aoc.common.constants.LoginConstant;
import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.common.util.ErrorCode;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoForListDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApplyInfoForListParamDto;
import com.gome.axwl.aoc.entity.dto.carrierSettle.CsApprovalParamDto;
import com.gome.axwl.aoc.entity.po.CsApplyInfoPo;
import com.gome.axwl.aoc.facade.CarrierSettleFacade;
import com.gome.axwl.aoc.service.sso.ServerGomeSsoClientService;
import com.gome.axwl.aoc.web.util.CarrierSettleUtil;
import com.gome.axwl.aoc.web.util.ExcelUtil;
import com.gome.commons.core.ResultData;


/**
 * 项目名称：gome-axwl-aoc-web
 * 类名称：CarrierSettleController
 * 类描述：服务商入驻运营平台
 * @author chenjunjie
 * @since 2018-07-16
 */
@Api(tags = "服务商入驻运营平台")
@RestController
@RequestMapping(value = "carrierSettle")
public class CarrierSettleController {
    private final static Logger LOGGER = LoggerFactory.getLogger(CarrierSettleController.class);
    @Autowired
    private CarrierSettleFacade carrierSettleFacade;
    @Autowired
    private ServerGomeSsoClientService ssoClientService;



    @ApiOperation(value = "服务商名称查询", notes = "development by chenjunjie")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "settleName", value = "服务商模糊查找匹配名称", paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/querySettleName", method = RequestMethod.GET)
    public ResultData<List<String>> querySettleName(String settleName){
        return carrierSettleFacade.querySettleName(settleName);
    }


    @ApiOperation(value = "查询申请单详情", notes = "development by yinyuxin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applyInfoId", value = "单子id", paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getApprovalDetailById", method = RequestMethod.GET)
    public ResultData<CsApplyInfoDto> getApprovalDetailById(Integer applyInfoId){
        return carrierSettleFacade.getApprovalDetailById(applyInfoId);
    }


    @ApiOperation(value = "审核列表", notes = "development by yinyuxin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carrrierSettleName", value = "服务商名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query",dataType="Date"),
            @ApiImplicitParam(name = "endTime",  value = "结束时间", paramType = "query",dataType="Date"),
            @ApiImplicitParam(name = "settleInviteNo", value = "入驻邀请码", paramType = "query",dataType="String"),
            @ApiImplicitParam(name = "id", value = "字典表id", paramType = "query",dataType="int"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", paramType = "query",dataType="int"),
            @ApiImplicitParam(name = "pageSize",value = "当前页条数", paramType = "query",dataType="int")
    })
    @RequestMapping(value = "/getApplyList", method = RequestMethod.GET)
    public ResultData<PageResultDto<CsApplyInfoForListDto>> getApplyList(CsApplyInfoForListParamDto csApplyInfoForListParamDto, HttpServletRequest request, HttpServletResponse response){
        LOGGER.info("接收到查询服务商入驻审批列表请求-->getApplyList()-->param:{}",BeanJsonUtil.obj2String(csApplyInfoForListParamDto));
        AccountInfo accountInfo = (AccountInfo)request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        if(accountInfo == null) {
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);
            accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
        }
        csApplyInfoForListParamDto.setApprovalUserNo(accountInfo.getAccountNo());
        csApplyInfoForListParamDto.setApprovalUsersInviteNo(accountInfo.getInvitationCode());
        return carrierSettleFacade.queryCsApplyInfoList(csApplyInfoForListParamDto);
    }


    @ApiOperation(value = "运营审核人转移", notes = "development by yinyuxin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applyInfoId", value = "申请单主键id", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "destinationNo", value = "转移人账号编码NO.", paramType = "query",dataType="String"),
    })
    @RequestMapping(value = "/transfer", method = RequestMethod.GET)
    public ResultData<Void> transfer(Integer applyInfoId, String destinationNo,HttpServletRequest request,HttpServletResponse response){
        AccountInfo accountInfo = (AccountInfo)request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        if(accountInfo == null) {
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);
            accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
        }
        String operationUserNo=accountInfo.getAccountNo();
        return carrierSettleFacade.transferApplyUser(applyInfoId, operationUserNo,destinationNo);
    }



    @ApiOperation(value = "审批入驻申请单",notes = "development by yinyuxin")
    @RequestMapping(value = "approvalApplyInfo",method=RequestMethod.POST)
    public  ResultData<Void> approvalApplyInfo(@RequestBody CsApprovalParamDto csApprovalParamDto,HttpServletRequest request,HttpServletResponse response){
        LOGGER.info("接收到审批入驻申请单请求-->approvalApplyInfo()-->param:{}",BeanJsonUtil.obj2String(csApprovalParamDto));
        AccountInfo accountInfo = (AccountInfo)request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        if(accountInfo == null) {
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);
            accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
        }
        csApprovalParamDto.setApprovalUserNo(accountInfo.getAccountNo());
        return carrierSettleFacade.approvalApplyInfo(csApprovalParamDto);
    }


    @ApiOperation(value = "邀请人查询",notes = "development by chenjunjie")
    @RequestMapping(value = "/findInviter",method=RequestMethod.GET)
    ResultData<List<Account>> findInviter(String parm){
        return carrierSettleFacade.findInviter(parm);
    }



    @ApiOperation(value = "申请单详情批量导出", notes = "development by liuxiaobo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applyInfoIdList", value = "申请单主键id集合", paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/applyInfoExport", method = RequestMethod.GET)
    public ResultData<Integer> transfer(@RequestParam List<Integer> applyInfoIdList, HttpServletResponse response){
        if (applyInfoIdList == null || applyInfoIdList.isEmpty()) {
            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
        }
        List<CsApplyInfoPo> infos = carrierSettleFacade.queryByIds(applyInfoIdList);
        String fileName = "服务商入驻详情.xlsx"; // 文件名
        String[] title = new String[] { "项目", "详情", "备注" };// 标题
        String[] filed = new String[] { "property", "value", "describe" };
        XSSFWorkbook wb = new XSSFWorkbook();
        for (CsApplyInfoPo info : infos) {
            String sheetName = info.getCarrrierSettleName();
            List<Map<String, Object>> data = CarrierSettleUtil.wrapCsApplyInfoData(info);
            wb = ExcelUtil.getXSSFWorkbook(sheetName, title, filed, data, wb);
        }
        // 将文件存到指定位置
        try {
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultData.newSuccessResultData();
    }


}
